<template>
  <div style="padding:20px;">
    <el-tabs>
      <el-tab-pane label="订单统计">
        <div class="app-container">
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="4"
              ><span class="el-custom-title"
                >需求统计</span
              ></el-col
            >
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-document"
                  class="el-button--mini"
                  @click="handleCreate"
                  >订单到料详情</el-button
                >
                <el-button type="primary"
                  icon="el-icon-edit"
                 size="mini" @click="handleUpdate()">
                  编辑
                </el-button>
                <el-button
                  type="primary"
                  icon="el-icon-first-aid-kit"
                  class="el-button--mini"
                  @click="ui_create"
                  >保存</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                   icon="el-icon-delete"
                  @click="ui_delete(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              ref="dataTable"
              v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="排产周期"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.schedulePeriod }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="订单编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.orderNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="产品编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.productNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="物料编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.materialNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="物料名称"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.materialName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="物料规格"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.materialModel }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="需求量"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.requireAmount }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="排产量"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.productAmount }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="最晚到料日期" width="95">
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.arriveDate | formatDate }}
                  </span>
                  <el-date-picker
                    v-model="scope.row.arriveDate"
                    type="date"
                    placeholder="选择日期"
                    @change="handleDateChange(scope.$index, scope.row)"
                    v-if="scope.row.isDirty"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第一周需求量 "
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.firstWeekRequireAmount }}
                  </span>

                  <el-input
                    v-model="scope.row.firstWeekRequireAmount"
                    placeholder="请输入需求数量"
                    @input="
                      handleEditChange(
                        scope.$index,
                        scope.row.firstWeekRequireAmount
                      )
                    "
                    v-if="scope.row.isDirty"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第一周到料日期"
                width="110"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.firstWeekArriveDate | formatDate }}
                  </span>

                  <el-date-picker
                    v-model="scope.row.firstWeekArriveDate"
                    type="date"
                    placeholder="选择日期"
                    @change="handleDateChange(scope.$index, scope.row)"
                    v-if="scope.row.isDirty"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第二周需求量"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.secondWeekRequireAmount }}
                  </span>

                  <el-input
                    v-model="scope.row.secondWeekRequireAmount"
                    placeholder="请输入需求数量"
                    @input="
                      handleEditChange(
                        scope.$index,
                        scope.row.secondWeekRequireAmount
                      )
                    "
                    v-if="scope.row.isDirty"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第二周到料日期"
                width="110"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.secondWeekArriveDate | formatDate }}
                  </span>

                  <el-date-picker
                    v-model="scope.row.secondWeekArriveDate"
                    type="date"
                    placeholder="选择日期"
                    @change="handleDateChange(scope.$index, scope.row)"
                    v-if="scope.row.isDirty"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第三周需求量"
                width="110"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.thirdWeekRequireAmount }}
                  </span>

                  <el-input
                    v-model="scope.row.thirdWeekRequireAmount"
                    placeholder="请输入需求数量"
                    @input="
                      handleEditChange(
                        scope.$index,
                        scope.row.thirdWeekRequireAmount
                      )
                    "
                    v-if="scope.row.isDirty"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第三周到料日期"
                width="110"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.thirdWeekArriveDate | formatDate }}
                  </span>

                  <el-date-picker
                    v-model="scope.row.thirdWeekArriveDate"
                    type="date"
                    placeholder="选择日期"
                    @change="handleDateChange(scope.$index, scope.row)"
                    v-if="scope.row.isDirty"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第四周需求量"
                width="110"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.fourthWeekRequireAmount }}
                  </span>

                  <el-input
                    v-model="scope.row.fourthWeekRequireAmount"
                    placeholder="请输入需求数量"
                    @input="
                      handleEditChange(
                        scope.$index,
                        scope.row.fourthWeekRequireAmount
                      )
                    "
                    v-if="scope.row.isDirty"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="第四周到料日期"
                width="110"
                style="display:none;"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.isDirty == null || scope.row.isDirty == false
                    "
                  >
                    {{ scope.row.fourthWeekArriveDate | formatDate }}
                  </span>

                  <el-date-picker
                    v-model="scope.row.fourthWeekArriveDate"
                    type="date"
                    placeholder="选择日期"
                    @change="handleDateChange(scope.$index, scope.row)"
                    v-if="scope.row.isDirty"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.limit"
              :page-sizes="listQuery.pageSizes"
              @pagination="fetchData"
            />
          </el-row>
          <el-row>
            <wmsstocklist></wmsstocklist>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="物料统计"> </el-tab-pane>
    </el-tabs>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="iid" prop="iid">
          <el-input v-model="temp.iid" />
        </el-form-item>
        <el-form-item label="isdmrpdtlid" prop="isdmrpdtlid">
          <el-input v-model="temp.isdmrpdtlid" />
        </el-form-item>
        <el-form-item label="spartname" prop="spartname">
          <el-input v-model="temp.spartname" />
        </el-form-item>
        <el-form-item label="imaterialdtlid" prop="imaterialdtlid">
          <el-input v-model="temp.imaterialdtlid" />
        </el-form-item>
        <el-form-item label="nwastage" prop="nwastage">
          <el-input v-model="temp.nwastage" />
        </el-form-item>
        <el-form-item label="nstdqty" prop="nstdqty">
          <el-input v-model="temp.nstdqty" />
        </el-form-item>
        <el-form-item label="nmrpqty" prop="nmrpqty">
          <el-input v-model="temp.nmrpqty" />
        </el-form-item>
        <el-form-item label="sremark" prop="sremark">
          <el-input v-model="temp.sremark" />
        </el-form-item>
        <el-form-item label="srealwidth" prop="srealwidth">
          <el-input v-model="temp.srealwidth" />
        </el-form-item>
        <el-form-item label="ibackupunitid" prop="ibackupunitid">
          <el-input v-model="temp.ibackupunitid" />
        </el-form-item>
        <el-form-item
          label="nunitconvertratebutobom"
          prop="nunitconvertratebutobom"
        >
          <el-input v-model="temp.nunitconvertratebutobom" />
        </el-form-item>
        <el-form-item label="srealgmm" prop="srealgmm">
          <el-input v-model="temp.srealgmm" />
        </el-form-item>
        <el-form-item label="srealmodel" prop="srealmodel">
          <el-input v-model="temp.srealmodel" />
        </el-form-item>
        <el-form-item label="sbomtype" prop="sbomtype">
          <el-input v-model="temp.sbomtype" />
        </el-form-item>
        <el-form-item label="iseq" prop="iseq">
          <el-input v-model="temp.iseq" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <router-view></router-view>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import { getRequiredMaterial } from "@/api/produce/schedulePlan/ProduceOrderProductPlanApi";
import moment from "moment";
import wmsstocklist from "@/views/wms/WMSStockList";
import {
  create as createMaterialRequire,
  createBatch,
  update as updateMaterialRequire,
  getList as getListRequiredMaterial
} from "@/api/supply/sdMaterialRequireApi";

export default {
  name: "materialRequiredList",
  components: { Pagination, wmsstocklist },
  data() {
    return {
      filterText: "",
      defaultProps: {
        children: "children",
        label: "erpMrpMaterial"
      },
      list: null,
      list2: null,
      listLoading: true,
      total: 0,
      total2: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [4, 6, 8]
      },
      currenterpMrpMaterialId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        arriveDate: [
          {
            required: true,
            message: "arriveDate不能为空！",
            trigger: "change"
          }
        ],
        firstWeekArriveDate: [
          {
            required: true,
            message: "firstWeekArriveDate不能为空！",
            trigger: "change"
          }
        ],
        firstWeekRequireAmount: [
          {
            required: true,
            message: "firstWeekRequireAmount不能为空！",
            trigger: "change"
          }
        ],
        fourthWeekArriveDate: [
          {
            required: true,
            message: "fourthWeekArriveDate不能为空！",
            trigger: "change"
          }
        ],
        fourthWeekRequireAmount: [
          {
            required: true,
            message: "fourthWeekRequireAmount不能为空！",
            trigger: "change"
          }
        ],
        secondWeekArriveDate: [
          {
            required: true,
            message: "secondWeekArriveDate不能为空！",
            trigger: "change"
          }
        ],
        secondWeekRequireAmount: [
          {
            required: true,
            message: "secondWeekRequireAmount不能为空！",
            trigger: "change"
          }
        ],
        thirdWeekArriveDate: [
          {
            required: true,
            message: "thirdWeekArriveDate不能为空！",
            trigger: "change"
          }
        ],
        thirdWeekRequireAmount: [
          {
            required: true,
            message: "thirdWeekRequireAmount不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: undefined,
        arriveDate: "",
        firstWeekArriveDate: "",
        firstWeekRequireAmount: 0,
        fourthWeekArriveDate: "",
        fourthWeekRequireAmount: 0,
        materialModel: "",
        materialName: "",
        materialNo: "",
        ngdnqty: 0,
        orderNo: "",
        planPeriod: "",
        productAmount: 0,
        productNo: "",
        requireAmount: 0,
        secondWeekArriveDate: "",
        secondWeekRequireAmount: 0,
        thirdWeekArriveDate: "",
        thirdWeekRequireAmount: 0
      },
      //表格變量
      lstSelected: [],
      queryConditions: {
        // produceLineId: "",
        schedulePeriod: "",
        schedulePeriodType: 1,
        orderNo: "",
        productNo: ""
      }
    };
  },
  filters: {
    formatDate(val) {
      if (val != null) {
        return moment(val).format("YYYY-MM-DD");
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
      //打上修改的标记
      for (let i = 0; i < this.list.length; i++) {
        debugger;
        let itm = this.list[i];
        let idx = this.lstSelected.findIndex(o => o.id == itm.id);
        if (idx > -1) {
          // itm.isDirty = true
        } else {
          itm.isDirty = false;
          this.list.splice(i, 1, itm);
        }
      }
      console.log(this.list);
    },
    fetchData() {
      this.listLoading = true;
      let params = { ...this.queryConditions };
      params.page = this.listQuery.page;
      params.size = this.listQuery.limit;
      getListRequiredMaterial(params).then(response => {
        this.list = response.data.records;
        console.log(this.list);
        this.total = response.data.total;
        this.listLoading = false;
      });
    },

    rowClick(row, column, event) {
      this.currentTherbligsTypeId = row.id;
      //this.getTherbligs()
    },
    ui_create() {
      let bError = false;
      this.list.forEach(v => {
        if (v.isDirty) {
          if (
            v.arriveDate == null ||
            v.firstWeekArriveDate == null ||
            v.firstWeekRequireAmount == null ||
            v.secondWeekArriveDate == null ||
            v.secondWeekRequireAmount == null ||
            v.thirdWeekArriveDate == null ||
            v.thirdWeekRequireAmount == null ||
            v.fourthWeekArriveDate == null ||
            v.fourthWeekRequireAmount == null
          ) {
            alert("请输入所有的需求量和日期！");
            bError = true;
            throw new Error("请输入所有的需求量和日期");
          }
          //到料日期要依次递增
          let t1 = moment(v.firstWeekArriveDate);
          let t2 = moment(v.secondWeekArriveDate);
          let t3 = moment(v.thirdWeekArriveDate);
          let t4 = moment(v.fourthWeekArriveDate);
          if (!(t2.isAfter(t1) && t3.isAfter(t2) && t4.isAfter(t3))) {
            alert("后期时间必须早于前期时间");
            bError = true;
            throw new Error("后期时间必须早于前期时间");
          }
          //判断各周需求量之和要等于需求量
          let totalAmount =
            parseFloat(v.firstWeekRequireAmount) +
            parseFloat(v.secondWeekRequireAmount) +
            parseFloat(v.thirdWeekRequireAmount) +
            parseFloat(v.fourthWeekRequireAmount);
          if (totalAmount < parseFloat(v.requireAmount)) {
            alert("各周需求量之和要大于或等于总需求量!");
            bError = true;
            throw new Error("各周需求量之和要等于总需求量");
          }
        }
      });
      if (bError) return;
      createBatch(this.list).then(() => {
        this.list.forEach(v => {
          v.isDirty = false;
        });
        this.$notify({
          title: "Success",
          message: "添加成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          update(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的erpMrpMaterial");
        return;
      }
      this.$confirm("是否要删除该菜单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let ids = [];
        this.lstSelected.map(function(elm) {
          ids.push(elm.id);
        });
        debugger;
        deleteBatch(ids).then(() => {
          ids.forEach(elm => {
            const index = this.list.findIndex(v => v.id === elm);
            this.list.splice(index, 1);
          });
          this.dialogFormVisible = false;
          this.$notify({
            title: "Success",
            message: "删除成功！",
            type: "success",
            duration: 2000
          });
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        arriveDate: "",
        firstWeekArriveDate: "",
        firstWeekRequireAmount: "",
        fourthWeekArriveDate: "",
        fourthWeekRequireAmount: "",
        materialModel: "",
        materialName: "",
        materialNo: "",
        ngdnqty: "",
        orderNo: "",
        planPeriod: "",
        productAmount: "",
        productNo: "",
        requireAmount: "",
        secondWeekArriveDate: "",
        secondWeekRequireAmount: "",
        thirdWeekArriveDate: "",
        thirdWeekRequireAmount: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length < 1) {
        this.$message.error("请先选择一条记录");
        return;
      }
      //打上修改的标记
      for (var i = 0; i < this.list.length; i++) {
        let itm = this.list[i];
        let idx = this.lstSelected.findIndex(o => o.id == itm.id);
        if (idx > -1) {
          itm.isDirty = true;
          this.list.splice(i, 1, itm);
        }
      }
    },
    handleEditChange(index, val) {
      this.list[index].isDirty = true;
      //设备
      if (!/^[0-9]\d*$/.test(val)) {
        this.$message.error("请输入不小于零的整数!");
        row.deviceAmount = 0;
        return;
      }
    },
    handleDateChange(index, row) {
      this.list[index].isDirty = true;
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
